package com.ita.tba.servlet;

import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ita.tba.po.Cart;
import com.ita.tba.po.Dish;
import com.ita.tba.po.DishCache;
import com.ita.tba.po.OrderList;
import com.ita.tba.service.Controller;
import com.ita.tba.service.impl.ControllerImpl;

/**
 * Servlet implementation class PayServlet
 */
public class PayServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private Controller controller = new ControllerImpl();   
    /**
     * @see HttpServlet#HttpServlet()
     */
    public PayServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String email = request.getParameter("email");
		double total = Double.valueOf(request.getParameter("total"));
		Date date = new Date();
		DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String time = format.format(date); 
		
		Map<Integer, Dish> dishCache = new HashMap<Integer, Dish>();
		dishCache = DishCache.dishCache;
		List<Dish> dishes = new ArrayList<Dish>();
		for (Integer did : dishCache.keySet()) {
			dishes.add(dishCache.get(did));
		}
		if (dishCache != null) {
			request.setAttribute("dishes", dishes);
		}
		
		int uid = controller.getUid(email);
		Cart cart = controller.getThisCart(uid);
		
		OrderList orderList = new OrderList(cart.getDidNum(), uid, total, time);
		boolean addSuccess = controller.addOrderList(orderList);
		if (addSuccess) {
			boolean clearSuccess = controller.clearCart(uid);
			if (clearSuccess) {
				Cart cart1 = controller.getThisCart(uid);
				Map<Integer, Integer> didNum = cart1.getDidNum();
				Map<String, Integer> dnameNum = new HashMap<String, Integer>();
				for (Integer did : didNum.keySet()) {
					dnameNum.put(dishCache.get(did).getDname(), didNum.get(did));
				}
				double totalPrice = cart1.getTotalPrice();
				dnameNum.put("TotalPrice RMB:", (int) totalPrice);
				request.setAttribute("cart", dnameNum);
			}
			
		}
		request.getRequestDispatcher("/jsp/index.jsp").forward(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
